<template>
  <div class="video-view" v-if="video">
    <div class="video-container">
      <video-player :video="video" />
      <div class="video-info">
        <h1 class="video-title">{{ video.title }}</h1>
        <div class="video-stats">
          <span>{{ formatViews(video.views) }} 次观看</span>
          <span>{{ formatDate(video.createdAt) }}</span>
        </div>
        <div class="video-actions">
          <el-button type="primary" plain :icon="isLiked ? 'ThumbUp' : 'Thumb'" @click="toggleLike">
            {{ video.likes }} 点赞
          </el-button>
          <el-button type="info" plain :icon="isCollected ? 'Star' : 'StarFilled'" @click="toggleCollect">
            收藏
          </el-button>
          <el-button type="success" plain :icon="isSubscribed ? 'Check' : 'Plus'" @click="toggleSubscribe">
            {{ isSubscribed ? '已订阅' : '订阅' }}
          </el-button>
          <el-button type="warning" plain icon="Share" @click="shareVideo">
            分享
          </el-button>
        </div>
        <el-divider />
        <div class="uploader-info">
          <div class="uploader-avatar">
            <el-avatar :size="50" :src="video.user.avatar"></el-avatar>
          </div>
          <div class="uploader-details">
            <h3 class="uploader-name">{{ video.user.name }}</h3>
            <p class="uploader-subscribers">{{ formatSubscribers(video.user.subscribers) }} 位订阅者</p>
          </div>
        </div>
        <div class="video-description">
          <p>{{ video.description }}</p>
        </div>
      </div>
    </div>
    
    <div class="comments-section">
      <h2>评论 ({{ video.comments.length }})</h2>
      <div class="comment-form">
        <el-input
          v-model="commentText"
          type="textarea"
          :rows="3"
          placeholder="添加评论..."
          :disabled="!isLoggedIn"
        />
        <div class="comment-actions">
          <el-button type="primary" @click="submitComment" :disabled="!isLoggedIn || !commentText.trim()">
            评论
          </el-button>
          <p v-if="!isLoggedIn" class="login-tip">请先 <router-link to="/login">登录</router-link> 后评论</p>
        </div>
      </div>
      
      <div class="comments-list">
        <div v-for="comment in video.comments" :key="comment._id" class="comment-item">
          <div class="comment-avatar">
            <el-avatar :size="40" :src="comment.user.avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
          </div>
          <div class="comment-content">
            <div class="comment-header">
              <span class="comment-author">{{ comment.user.name }}</span>
              <span class="comment-time">{{ formatDate(comment.createdAt) }}</span>
            </div>
            <p class="comment-text">{{ comment.text }}</p>
            <div class="comment-actions">
              <el-button text size="small" @click="likeComment(comment._id)">
                <el-icon><ThumbUp /></el-icon> {{ comment.likes }}
              </el-button>
              <el-button text size="small" @click="replyToComment(comment._id)">
                <el-icon><ChatDotRound /></el-icon> 回复
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="related-videos">
      <h2>推荐视频</h2>
      <div v-if="relatedVideos.length === 0" class="empty-state">
        <el-empty description="暂无推荐视频" />
      </div>
      <div v-else v-for="relatedVideo in relatedVideos" :key="relatedVideo._id" class="related-video-item">
        <video-card :video="relatedVideo" />
      </div>
    </div>
  </div>
  <div v-else class="loading-container">
    <el-skeleton :rows="10" animated />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from '@/services/axios'
import { ElMessage, ElAvatar, ElIcon, ElButton, ElInput, ElEmpty } from 'element-plus'
import { View, Star, StarFilled, Download, Warning } from '@element-plus/icons-vue'
// import { useUserStore } from '../store/user' // Removed import
import VideoPlayer from '../../components/user/VideoPlayer.vue' // Assuming VideoPlayer is in components/user

const route = useRoute()
const router = useRouter()
// const userStore = useUserStore() // Removed usage

// 用户登录状态
const isLoggedIn = computed(() => userStore.isLoggedIn) // Removed usage

// 视频数据
const video = ref(null)
const relatedVideos = ref([])
const loading = ref(true)

// 用户交互状态
const isLiked = ref(false)
const isCollected = ref(false)
const isSubscribed = ref(false)
const commentText = ref('')

// 获取视频数据
onMounted(async () => {
  const videoId = route.params.id
  await Promise.all([
    fetchVideoData(videoId),
    fetchRelatedVideos(videoId)
  ])
})

// 获取视频数据
const fetchVideoData = async (videoId) => {
  loading.value = true
  try {
    const response = await axios.get(`/api/videos/${videoId}`)
    video.value = response.data.video
    
    // 如果用户已登录，获取交互状态
    if (isLoggedIn.value) {
      const interactionResponse = await axios.get(`/api/videos/${videoId}/interaction`)
      const { isLiked: liked, isCollected: collected, isSubscribed: subbed } = interactionResponse.data
      isLiked.value = liked
      isCollected.value = collected
      isSubscribed.value = subbed
    }
  } catch (error) {
    console.error('获取视频信息失败:', error)
    let errorMessage = '获取视频信息失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
    router.push('/404')
  } finally {
    loading.value = false
  }
}

// 获取相关视频
const fetchRelatedVideos = async (videoId) => {
  try {
    const response = await axios.get(`/api/videos/${videoId}/related`)
    relatedVideos.value = response.data.videos || []
  } catch (error) {
    console.error('获取相关视频失败:', error)
    let errorMessage = '获取相关视频失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
    relatedVideos.value = []
  }
}



// 格式化观看次数
const formatViews = (views) => {
  if (views >= 1000000) {
    return (views / 1000000).toFixed(1) + '百万'
  } else if (views >= 10000) {
    return (views / 10000).toFixed(1) + '万'
  } else if (views >= 1000) {
    return (views / 1000).toFixed(1) + '千'
  } else {
    return views
  }
}

// 格式化订阅者数量
const formatSubscribers = (subscribers) => {
  if (subscribers >= 1000000) {
    return (subscribers / 1000000).toFixed(1) + '百万'
  } else if (subscribers >= 10000) {
    return (subscribers / 10000).toFixed(1) + '万'
  } else if (subscribers >= 1000) {
    return (subscribers / 1000).toFixed(1) + '千'
  } else {
    return subscribers
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) {
    return '1 天前'
  } else if (diffDays < 7) {
    return diffDays + ' 天前'
  } else if (diffDays < 30) {
    const weeks = Math.floor(diffDays / 7)
    return weeks + ' 周前'
  } else if (diffDays < 365) {
    const months = Math.floor(diffDays / 30)
    return months + ' 个月前'
  } else {
    const years = Math.floor(diffDays / 365)
    return years + ' 年前'
  }
}

// 交互方法
// 点赞视频
const toggleLike = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  
  try {
    const response = await axios.post(`/api/videos/${video.value._id}/like`, {
      action: isLiked.value ? 'unlike' : 'like'
    })
    
    isLiked.value = !isLiked.value
    video.value.likes = response.data.likes
    ElMessage.success(isLiked.value ? '点赞成功' : '已取消点赞')
  } catch (error) {
    console.error('点赞操作失败:', error)
    let errorMessage = '操作失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
  }
}

// 收藏视频
const toggleCollect = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  
  try {
    const response = await axios.post(`/api/videos/${video.value._id}/collect`, {
      action: isCollected.value ? 'uncollect' : 'collect'
    })
    
    isCollected.value = !isCollected.value
    ElMessage.success(isCollected.value ? '收藏成功' : '已取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    let errorMessage = '操作失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
  }
}

// 订阅频道
const toggleSubscribe = async () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  
  try {
    const response = await axios.post(`/api/users/${video.value.user._id}/subscribe`)
    
    isSubscribed.value = !isSubscribed.value
    video.value.user.subscribers = response.data.subscribers
    ElMessage.success(isSubscribed.value ? '订阅成功' : '已取消订阅')
  } catch (error) {
    console.error('订阅操作失败:', error)
    let errorMessage = '操作失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
  }
}

// 分享视频
const shareVideo = () => {
  // 复制视频链接到剪贴板
  const videoUrl = window.location.href
  navigator.clipboard.writeText(videoUrl)
    .then(() => ElMessage.success('视频链接已复制到剪贴板'))
    .catch(() => ElMessage.error('复制链接失败'))
}

// 提交评论
const submitComment = async () => {
  if (!commentText.value.trim()) {
    return
  }
  
  try {
    const response = await axios.post(`/api/videos/${video.value._id}/comments`, {
      text: commentText.value.trim()
    })
    
    // 添加新评论到列表
    video.value.comments.unshift(response.data.comment)
    commentText.value = ''
    ElMessage.success('评论成功')
  } catch (error) {
    console.error('评论失败:', error)
    let errorMessage = '评论失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
  }
}

// 点赞评论
const likeComment = async (commentId) => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  
  try {
    const response = await axios.post(`/api/comments/${commentId}/like`)
    
    // 更新评论点赞数
    const comment = video.value.comments.find(c => c._id === commentId)
    if (comment) {
      comment.likes = response.data.likes
      ElMessage.success('点赞成功')
    }
  } catch (error) {
    console.error('评论点赞失败:', error)
    let errorMessage = '操作失败'
    if (error.response?.data?.error) {
      errorMessage = error.response.data.error
    }
    ElMessage.error(errorMessage)
  }
}

// 回复评论
const replyToComment = (commentId) => {
  // 设置评论框的占位符，提示用户正在回复
  const comment = video.value.comments.find(c => c._id === commentId)
  if (comment) {
    commentText.value = `@${comment.user.name} `
  }
}
</script>

<style scoped>
.video-view {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.video-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.video-info {
  padding: 0 10px;
}

.video-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #333;
}

.video-stats {
  display: flex;
  gap: 15px;
  color: #606060;
  margin-bottom: 15px;
}

.video-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.uploader-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.uploader-avatar {
  margin-right: 15px;
}

.uploader-name {
  margin: 0 0 5px 0;
  font-size: 18px;
  font-weight: 500;
}

.uploader-subscribers {
  margin: 0;
  color: #606060;
}

.video-description {
  margin-bottom: 20px;
  line-height: 1.5;
  color: #333;
}

.comments-section {
  margin-bottom: 30px;
}

.comment-form {
  margin-bottom: 20px;
}

.comment-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}

.login-tip {
  margin: 0;
  color: #606060;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  display: flex;
  gap: 15px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  margin-bottom: 5px;
}

.comment-author {
  font-weight: 500;
  margin-right: 10px;
}

.comment-time {
  color: #606060;
  font-size: 14px;
}

.comment-text {
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.related-videos {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.related-video-item {
  margin-bottom: 15px;
}

.loading-container {
  padding: 20px;
}

@media (min-width: 992px) {
  .video-container {
    flex-direction: row;
    align-items: flex-start;
  }
  
  .video-player {
    flex: 2;
  }
  
  .video-info {
    flex: 1;
    padding: 0 20px;
  }
  
  .video-view {
    display: grid;
    grid-template-columns: 2fr 1fr;
    grid-template-areas:
      "video related"
      "comments related";
    gap: 30px;
  }
  
  .video-container {
    grid-area: video;
    flex-direction: column;
  }
  
  .comments-section {
    grid-area: comments;
  }
  
  .related-videos {
    grid-area: related;
  }
}
</style>